App({
  globalData: {
    isLoggedIn: false,
    token: null,
    userInfo: null,
    links: [],
    profile: {
      nickname: '',
      bio: '',
      occupation: '',
      location: '',
      website: ''
    }
  },

  onLaunch() {
    // 检查本地存储的登录状态
    const token = wx.getStorageSync('token')
    const userInfo = wx.getStorageSync('userInfo')
    
    if (token && userInfo) {
      this.globalData.isLoggedIn = true
      this.globalData.token = token
      this.globalData.userInfo = userInfo
      
      // 验证token是否有效
      this.checkToken()
    }
  },

  // 检查token是否有效
  checkToken() {
    // TODO: 替换为实际的服务器接口地址
    const apiUrl = 'https://your-api-domain.com/api/check-token'
    
    wx.request({
      url: apiUrl,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${this.globalData.token}`
      },
      success: (res) => {
        if (!res.data.success) {
          // token无效，清除登录状态
          this.clearLoginState()
          // 跳转到登录页
          wx.reLaunch({
            url: '/pages/login/login'
          })
        } else {
          // token有效，加载用户数据
          this.loadUserData()
        }
      },
      fail: () => {
        // 请求失败，假设token仍然有效，继续使用
        this.loadUserData()
      }
    })
  },

  // 加载用户数据
  loadUserData() {
    // TODO: 替换为实际的服务器接口地址
    const apiUrl = 'https://your-api-domain.com/api/user/data'
    
    wx.request({
      url: apiUrl,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${this.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          // 更新全局数据
          this.globalData.profile = res.data.profile
          this.globalData.links = res.data.links
        }
      }
    })
  },

  // 清除登录状态
  clearLoginState() {
    this.globalData.isLoggedIn = false
    this.globalData.token = null
    this.globalData.userInfo = null
    this.globalData.profile = {
      nickname: '',
      bio: '',
      occupation: '',
      location: '',
      website: ''
    }
    this.globalData.links = []
    
    // 清除本地存储
    wx.removeStorageSync('token')
    wx.removeStorageSync('userInfo')
  }
}) 